#!/bin/bash

set -e
sudo -v

CUR_DIR=$PWD
WORK_DIR=$PWD/code
PATCH_DIR=$PWD/prc_patch
SETUP_DIR=$PWD/setup

# Variable for displaying log
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
MAGENTA=$(tput setaf 5)
NC=$(tput sgr0)
BOLD=$(tput bold)
INFO=$(tput setaf 3)
FILE_NAME=$0
eii_ver=''


Usage()
{
    echo
	echo "${BOLD}${INFO}==================================================================================${NC}"
    echo
	echo "${BOLD}${GREEN}Usage :: $FILE_NAME -h [OPTION...] ${NC}"
    echo
	echo "${INFO}List of available options..."
    echo
    echo "${INFO}--eii			install the eii version"${NC}
    echo
	echo "${INFO}--help			display this help and exit"${NC}
    echo
	echo "${INFO}-h			display this help and exit"${NC}
	echo "use cases sample..."
        echo "${BOLD}${MAGENTA}

                1. install eii
                $FILE_NAME --eii=v2.5
                $FILE_NAME --eii=v2.6
                $FILE_NAME --eii=v2.6.1
                $FILE_NAME --eii=v3.0

        "
    
	echo "${INFO}===================================================================================${NC}"
	exit 1
}


parse_commandLine_args()
{
	if [ $# == "0" ];then
		return;
	fi
	
	# echo "${INFO}Reading the command line args...${NC}"
	for ARGUMENT in "$@"
	do
	    KEY=$(echo $ARGUMENT | cut -f1 -d=)
	    VALUE=$(echo $ARGUMENT | cut -f2 -d=)   

	    case "$KEY" in
		    --eii) eii_ver=$VALUE ;;   
		    --help) Usage ;; 
            -h) Usage ;; 
		     *) echo "${RED}Invalid arguments passed..${NC}"; Usage; ;;  
	    esac    
	done
}


display_progress () {
    echo " "
    echo "-----------------------------------------------"
    echo $1
    echo "-----------------------------------------------"
    echo " "
}

make_work_dir () {
    rm -rf $WORK_DIR
    mkdir -p $WORK_DIR
}

install_dependency () {
    # Go to work dir
    cd $WORK_DIR

    # Install tools
    sudo apt update
    sudo apt install -y curl git vim wget

    # Install repo
    curl https://storage.googleapis.com/git-repo-downloads/repo > repo
    sudo mv repo /bin/repo
    sudo chmod a+x /bin/repo

    # Set python (Ubuntu 20.04 needs)
    if [ ! -f "/usr/bin/python" ]; then
        sudo ln -s /usr/bin/python3 /usr/bin/python
    fi

    # Config git info
    if [ -z $(git config user.email) ]; then
        git config --global user.email "test@example.com"
    fi
    if [ -z $(git config user.name) ]; then
        git config --global user.name "test"
    fi
    # Disable CA verify
    git config --global http.sslverify false
    # Set store username
    git config --global credential.helper store

    # Check repo version
    repo --version
}

download_eii_source_code () {
    # Go to work dir
    cd $WORK_DIR

    # Change REPO_URL for PRC network
    export REPO_URL="https://gerrit-googlesource.lug.ustc.edu.cn/git-repo"
    # export REPO_URL="https://gerrit-googlesource.proxy.ustclug.org/git-repo"

    # Init eii repo
    if [ -z $eii_ver ];then
        echo y | repo init -u "https://gitee.com/open-edge-insights/eii-manifests.git"
    else
        echo y | repo init -u "https://gitee.com/open-edge-insights/eii-manifests.git" -b refs/tags/$eii_ver
    fi

    # Apply PRC changes to manifest file
    replace_tag=(`grep -nr "https://github.com" | awk -F ':' '{print $1}'| grep -v Binary`)
    if [ ${#replace_tag[@]} -gt 0 ];then
        grep -nr "https://github.com" | awk -F ':' '{print $1}' | grep -v Binary | xargs sed -i 's!github!gitee!g'
    fi
    # Change for "intel" repo
    sed -i 's/intel/mirrors_intel/g' $WORK_DIR/.repo/manifests/default.xml

    # Sync eii source code
    repo sync
}

apply_prc_change_to_eii_source_code () {
    # Go to work dir
    cd $WORK_DIR

    # Run change source script
    cp $PATCH_DIR/source_config/eii-prc-source-$eii_ver.json .
    cp $PATCH_DIR/changesource.sh .
    chmod +x changesource.sh
    ./changesource.sh eii-prc-source-$eii_ver.json
    rm -rf changesource.sh eii-prc-source-$eii_ver.json
}

install_eii_pre_req () {
    # Go to setup dir
    cd $SETUP_DIR

    # Run install script
    ./install_eii_deps.sh
}

# --- beginning of script ---

if [ $# -ne "0" ];then
	parse_commandLine_args "$@"
else
	echo "${BOLD}${INFO}Please type at least 1 params${NC}"
	echo "${BOLD}${INFO}Usage :: $FILE_NAME -h [OPTION...] ${NC}"
    exit 1
fi


startTime=`date +%Y%m%d-%H:%M:%S`
startTime_s=`date +%s`

# Main Process
display_progress "Start to install eii"
make_work_dir
install_dependency
download_eii_source_code
apply_prc_change_to_eii_source_code
install_eii_pre_req
display_progress "Success to install eii"

endTime=`date +%Y%m%d-%H:%M:%S`
endTime_s=`date +%s`
sumTime=$[ $endTime_s - $startTime_s ]
echo "$startTime ---> $endTime" "Total:$sumTime seconds"
echo " "
echo "Please restart to apply the change: 'sudo reboot'"
